﻿using Newtonsoft.Json.Linq;
using LibreHardwareMonitor.Hardware;
using System;
using System.IO;
using System.Threading;

namespace cpu_temp
{

    public class UpdateVisitor : IVisitor
    {
        public void VisitComputer(IComputer computer)
        {
            computer.Traverse(this);
        }
        public void VisitHardware(IHardware hardware)
        {
            hardware.Update();
            foreach (IHardware subHardware in hardware.SubHardware) subHardware.Accept(this);
        }
        public void VisitSensor(ISensor sensor) { }
        public void VisitParameter(IParameter parameter) { }
    }

    
    class Program
    {
        static void Main()
        {
            // 实例化硬件类
            Computer myComputer = new Computer
            {
                IsCpuEnabled = true,
                IsGpuEnabled = true,
                IsMemoryEnabled = true,
                IsMotherboardEnabled = true,
                IsControllerEnabled = true,
                IsNetworkEnabled = true,
                IsStorageEnabled = true
            };

            // 有时候实例化硬件会出错，尝试10次
            for (int i = 1; i <= 10; i++)
            {
                try
                {
                    myComputer.Open();
                    myComputer.Accept(new UpdateVisitor());
                }
                catch
                {
                    if (i == 10)
                    {
                        return;
                    }
                    System.Threading.Thread.Sleep(1500);
                    continue;
                }
            }
            // 传输的JSON初始化
            JArray result = new JArray();

            string fan_speed = "";
            // Console.Clear();
            foreach (var hardwareItem in myComputer.Hardware)
            {
                // 提取风扇信息
                // Console.WriteLine(hardwareItem.HardwareType + "型号是：" + hardwareItem.Name);
                // 从主板上获取南桥芯片信息，然后根据南桥下面的Fan类型（要注意区分CPU风扇和系统风扇）
                // 南桥芯片信息
                if (hardwareItem.HardwareType == HardwareType.Motherboard)
                {
                    JObject cpu_fan = new JObject();
                    foreach (var Norbrige in hardwareItem.SubHardware)
                    {
                        foreach (var fan_sensor in Norbrige.Sensors)
                        {
                            // 风扇字段，不同的主板，显示不一样
                            // 先从大类开始找，转速大于0的，都记录下来
                            var tmp_str = fan_sensor.SensorType.ToString();
                            if (tmp_str == "Fan")
                            {
                                // 明确有CPU风扇字段的
                                if (fan_sensor.Name == "CPU Fan" && fan_sensor.Value > 0)
                                {
                                    // Console.WriteLine("CPU 风扇转速：" + fan_sensor.Value);
                                    fan_speed = fan_sensor.Value.ToString();
                                    break;
                                }
                                else if (fan_sensor.Value > 0)
                                {
                                    // Console.WriteLine("CPU 风扇转速：" + fan_sensor.Value);
                                    fan_speed = fan_sensor.Value.ToString();
                                }
                                else
                                {
                                    // Console.WriteLine("没有读取到风扇转速或者转速为0");
                                    fan_speed = "";
                                }
                            }
                        }
                        cpu_fan.Add(hardwareItem.HardwareType.ToString(), fan_speed);
                        // result.Add(cpu_fan);
                    }
                }
                // 非主板类硬件
                // 查找温度信息
                else
                {
                    // Console.WriteLine(hardwareItem.HardwareType + ":\n");

                    JObject hardware_type = new JObject();
                    JObject tempera = new JObject();
                    string tmp_hardware_type = "";
                    Boolean flag = false;
                    foreach (var sensor in hardwareItem.Sensors)
                    {                        
                        string tmp_tempeara = "";
                        // 类型是温度
                        if (sensor.SensorType == SensorType.Temperature)
                        {
                            string tmp_string = sensor.Name.ToString();
                            // CPU温度
                            if (hardwareItem.HardwareType == HardwareType.Cpu && tmp_string.Contains(" Max"))
                            {
                                // Console.WriteLine(hardwareItem.Name + "的温度：" + sensor.SensorType + ":" + sensor.Value);
                                tmp_tempeara = sensor.Value.ToString();
                                tmp_hardware_type = "CPU";
                            }
                            //显卡温度
                            else if (hardwareItem.HardwareType == HardwareType.GpuAmd || hardwareItem.HardwareType == HardwareType.GpuIntel || hardwareItem.HardwareType == HardwareType.GpuNvidia)
                            {
                                if (sensor.Name == "GPU Core")
                                {
                                    // Console.WriteLine(hardwareItem.Name + "的温度：" + sensor.SensorType + ":" + sensor.Value);
                                    tmp_tempeara = sensor.Value.ToString();
                                    tmp_hardware_type = "GPU";
                                }
                            }
                            // 硬盘温度
                            else if (hardwareItem.HardwareType == HardwareType.Storage && sensor.Name == "Temperature")
                            {
                                // Console.WriteLine(hardwareItem.Name + "的温度：" + sensor.SensorType + ":" + sensor.Value);
                                tmp_tempeara = sensor.Value.ToString();
                                tmp_hardware_type = "HDD/SSD";
                            }
                        }
                        if (tmp_tempeara != "")
                        {
                            tempera.Add("Temperature", tmp_tempeara);
                            tempera.Add("Nmae", hardwareItem.Name.ToString());
                            flag = true;
                        }
                    }
                    if (flag)
                    {
                        hardware_type.Add(tmp_hardware_type, tempera);
                        result.Add(hardware_type);
                    }   
                }

            }
            myComputer.Close();
            Console.Write(result.ToString());
            // System.Threading.Thread.Sleep(15000);
        }
    }//end main
}

/*
                // if (args[0] == "discovery")
                if (1 == 1)
                {
                    Computer myComputer = new Computer();
                    myComputer.Open();

                    //启动主板监测
                    myComputer.MainboardEnabled = true;
                    //启动CPU监测
                    myComputer.CPUEnabled = true;
                    //启动内存监测
                    myComputer.RAMEnabled = true;
                    //启动GPU监测
                    myComputer.GPUEnabled = true;
                    //启动风扇监测
                    myComputer.FanControllerEnabled = true;
                    //启动硬盘监测
                    myComputer.HDDEnabled = true;

                    JObject r = new JObject();
                    JArray data = new JArray();
                    // 遍历所有硬件
                    for (int i = 0; i < myComputer.Hardware.Length; i++)
                    {
                        // 如果发现CPU
                        if (myComputer.Hardware[i].HardwareType == HardwareType.CPU || 1 == 1)
                        {
                            Console.Write(myComputer.Hardware[i].HardwareType + ":");
                            // Console.Write(myComputer.Hardware[i].Identifier + "\n");
                            // Console.Write(myComputer.Hardware[i].Parent + "\n");
                            // Console.Write(myComputer.Hardware[i].SubHardware + "\n");
                            // Console.Write(myComputer.Hardware[i].Sensors + "\n");
                            foreach (var sensor in myComputer.Hardware[i].Sensors)
                            {
                                Console.WriteLine(sensor.Name + "的" + sensor.SensorType + "是" + sensor.Value);
                            }
                            // 遍历传感器
                            for (int j = 0; j < myComputer.Hardware[i].Sensors.Length; j++)
                            {                                
                                continue;
                                // 如果发现温度
                                Console.Write(myComputer.Hardware[i].Sensors[j].SensorType + "\n");
                                if (myComputer.Hardware[i].Sensors[j].SensorType == SensorType.Temperature)
                                {
                                    Console.Write("发现CPU 温度信息");
                                    JObject cpu = new JObject();
                                    cpu.Add("{#INDEX}", data.Count + 1);
                                    cpu.Add("{#CPUID}", i.ToString());
                                    cpu.Add("{#CPUNAME}", myComputer.Hardware[i].Sensors[j].Name);
                                    cpu.Add("{#CPUTEMP}", myComputer.Hardware[i].Sensors[j].Value.ToString());
                                    data.Add(cpu);
                                }
                            }
                        }
                    }
                    myComputer.Close();
                    r.Add("data", data);
                    Console.Write(r.ToString());
                    File.WriteAllText("cpu.temp", r.ToString());
                }
                else
                {
                    if (File.Exists("cpu.temp"))
                    {
                        JObject json = Newtonsoft.Json.JsonConvert.DeserializeObject<JObject>(File.ReadAllText("cpu.temp"));
                        foreach (var item in json.Value<JArray>("data"))
                        {
                            if (args[0] == item.Value<string>("{#INDEX}"))
                            {
                                Console.Write(item.Value<string>("{#CPUTEMP}"));
                            }
                        }
                    }
                }
            }
            System.Threading.Thread.Sleep(50000);
        }        
    }
}
*/